<template>
  <div class="second-hand-book-home">
    <!-- 顶部导航栏 - 增加二手书特色 -->
    <van-nav-bar class="book-nav-bar">
      <template #left>
        <div class="logo-area">
          <span class="logo-text">淘书巴士</span>
          <van-tag round type="danger">二手</van-tag>
        </div>
      </template>
      <template #right>
        <van-search
          v-model="searchValue"
          placeholder="搜二手书/作者/出版社/ISBN"
          shape="round"
          background="#f5e8d0"
          @search="onSearch"
          @input="handleSearchInput"
          class="book-search"
          show-action
        >
          <template #action>
            <div @click="clearSearch" class="search-action" v-if="searchValue.trim()">
              取消
            </div>
          </template>
        </van-search>
      </template>
    </van-nav-bar>

    <!-- 搜索结果区域 -->
    <div v-if="searchValue.trim()" class="search-result-container">
      <!-- 无搜索结果提示 -->
      <div v-if="filteredBooks.length === 0" class="empty-result">
        <van-icon name="search" size="40" color="#ccc" />
        <p>没有找到匹配的二手书</p>
        <van-button 
          round 
          type="primary" 
          color="#8b4513" 
          @click="clearSearch"
          size="small"
        >
          重新搜索
        </van-button>
      </div>

      <!-- 搜索结果列表 -->
      <div v-else class="search-result-list">
        <div 
          v-for="(book, index) in filteredBooks" 
          :key="index" 
          class="book-card"
          @click="onDetail(book)"
        >
          <div class="book-image">
            <van-image 
              :src="`/img/sp${(index % 6) + 1}.jpg`" 
              width="100" 
              height="140" 
              fit="cover" 
              radius="4"
            />
            <div class="book-tags">
              <van-tag v-if="book.discount" color="#f44" text-color="white" size="small">
                {{ book.discount }}
              </van-tag>
              <van-tag color="#8b4513" text-color="white" size="small">
                {{ book.condition }}
              </van-tag>
            </div>
          </div>
          <div class="book-info">
            <div class="title van-multi-ellipsis--l2">{{ book.title }}</div>
            <div class="author">{{ book.author || '未知作者' }}</div>
            <div class="price-section">
              <div class="current-price">¥{{ book.price }}</div>
              <div class="original-price" v-if="book.originalPrice">
                ¥{{ book.originalPrice }}
              </div>
            </div>
            <div class="sales">
              <van-icon name="fire-o" size="12" />
              <span>已售 {{ book.sales || 0 }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 首页内容区域 - 仅在无搜索内容时显示 -->
    <div v-else>
      <!-- 轮播 - 增加二手书特色标语 -->
      <div class="swipe-container">
        <van-swipe :autoplay="4000" class="book-swipe">
          <!-- 修改图片路径 -->
          <van-swipe-item v-for="(item, i) in carouselItems" :key="i" @click="onDetail(item)">
            <van-image :src="item.img" width="100%" />
          </van-swipe-item>
        </van-swipe>
        <div class="swipe-notice">
          <van-notice-bar left-icon="volume-o" scrollable>
            温馨提示：所有二手书均经过消毒处理，支持7天无理由退换
          </van-notice-bar>
        </div>
      </div>

      <!-- 功能入口 -->
      <div class="menu-section">
        <h3 class="section-title">
          <van-icon name="apps-o" color="#8b4513" /> 快捷功能
        </h3>
        <van-grid :border="false" :column-num="4" clickable>
          <van-grid-item icon="scan" text="扫码卖书" to="/sell">
            <template #icon>
              <div class="category-icon">
                <van-icon name="scan" size="24"  color="#8b4513"/>
              </div>
            </template>
          </van-grid-item>
          <van-grid-item icon="chat" text="联系客服" to="/chat">
            <template #icon>
              <div class="category-icon">
                <van-icon name="chat" size="24"  color="#8b4513"/>
              </div>
            </template>
          </van-grid-item>
          <van-grid-item icon="star-o" text="我的收藏" to="/favorite">
            <template #icon>
              <div class="category-icon">
                <van-icon name="star-o" size="24" color="#8b4513"/>
              </div>
            </template>
          </van-grid-item>
          <van-grid-item icon="comment" text="意见反馈" to="/connect">
            <template #icon>
              <div class="category-icon">
                <van-icon name="comment" size="24" color="#8b4513"/>
              </div>
            </template>
          </van-grid-item>
        </van-grid>
      </div>
      

      <!-- 特价专区 -->
      <div class="product-section">
        <h3 class="section-title">
          <van-icon name="discount" color="#f44" /> 特价专区
        </h3>
        <div class="product-list">
          <div v-for="(item, index) in discountItems" :key="index" class="product-card" @click="onDetail(item)">
            <!-- 修改图片路径 -->
            <van-image :src="item.img" width="100%" height="160" fit="cover" radius="4" />
            <div class="product-info">
              <div class="title van-multi-ellipsis--l2">{{ item.title }}</div>
              <div class="price-section">
                <div class="current-price">¥{{ item.price }}</div>
                <div class="original-price" v-if="item.originalPrice">
                  ¥{{ item.originalPrice }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 近新好书 -->
      <div class="product-section">
        <h3 class="section-title">
          <van-icon name="new-o" color="#07c160" /> 近新好书
        </h3>
        <div class="product-list">
          <div v-for="(item, index) in newConditionItems" :key="index" class="product-card" @click="onDetail(item)">
            <!-- 修改图片路径 -->
            <van-image :src="item.img" width="100%" height="160" fit="cover" radius="4" />
            <div class="product-info">
              <div class="title van-multi-ellipsis--l2">{{ item.title }}</div>
              <div class="price-section">
                <div class="current-price">¥{{ item.price }}</div>
                <div class="original-price" v-if="item.originalPrice">
                  ¥{{ item.originalPrice }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
  
      <!-- 热门转让 -->
      <div class="product-section">
        <h3 class="section-title">
          <van-icon name="fire-o" color="#ff976a" /> 热门转让
        </h3>
        <div class="product-list">
          <div v-for="(item, index) in hotSaleItems" :key="index" class="product-card" @click="onDetail(item)">
            <!-- 修改图片路径 -->
            <van-image :src="item.img" width="100%" height="160" fit="cover" radius="4" />
            <div class="product-info">
              <div class="title van-multi-ellipsis--l2">{{ item.title }}</div>
              <div class="price-section">
                <div class="current-price">¥{{ item.price }}</div>
                <div class="original-price" v-if="item.originalPrice">
                  ¥{{ item.originalPrice }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getHomeDataAPI } from "@/api/home.js";
import { Icon } from 'vant';

export default {
  components: {
    [Icon.name]: Icon
  },
  data() {
    return {
      searchValue: '',
      carouselItems: [],
      discountItems: [],  // 特价商品
      newConditionItems: [], // 近新商品
      hotSaleItems: [],  // 热门商品
      gridItems: [
        { icon: "/images/tsfltb.png", text: "教材教辅", to: "/category/textbook" },
        { icon: "/images/tsfltb.png", text: "文学小说", to: "/literatureNovel" },
        { icon: "/images/tsfltb.png", text: "考试用书", to: "/category/exam" },
        { icon: "/images/tsfltb.png", text: "儿童读物", to: "/category/children" },
        { icon: "/images/tsfltb.png", text: "人文社科", to: "/category/humanities" },
        { icon: "/images/tsfltb.png", text: "经济管理", to: "/category/economics" },
        { icon: "/images/tsfltb.png", text: "科学技术", to: "/category/science" },
        { icon: "/images/tsfltb.png", text: "艺术设计", to: "/category/art" },
        { icon: "/images/tsfltb.png", text: "生活休闲", to: "/category/life" },
        { icon: "/images/tsfltb.png", text: "外语学习", to: "/category/language" },
        { icon: "/images/tsfltb.png", text: "医学健康", to: "/category/medical" },
        { icon: "/images/tsfltb.png", text: "计算机", to: "/bookList" },
        { icon: "/images/tsfltb.png", text: "法律政治", to: "/category/law" },
        { icon: "/images/tsfltb.png", text: "历史地理", to: "/category/history" }
      ],
      currentPage: 0,
      itemsPerPage: 10,
      filteredBooks: [] // 搜索结果
    };
  },
  computed: {
    paginatedGridItems() {
      const pages = [];
      for (let i = 0; i < this.gridItems.length; i += this.itemsPerPage) {
        pages.push(this.gridItems.slice(i, i + this.itemsPerPage));
      }
      return pages;
    },
    // 合并所有书籍数据用于搜索
    allBooks() {
      return [
        ...this.discountItems,
        ...this.newConditionItems,
        ...this.hotSaleItems
      ];
    }
  },
  created() {
    getHomeDataAPI().then(result => {
      this.carouselItems = result.data.carouselItems
      
      // 模拟二手书特有数据
      this.discountItems = result.data.discountItems
      this.newConditionItems = result.data.newConditionItems
      this.hotSaleItems = result.data.hotSaleItems
    }).catch(() => {});
  },
  methods: {
    generateSecondhandBooks(discountRate, isDiscount, isNewCondition, isHot) {
      const mockTitles = [
        "经济学原理", "JavaScript高级程序设计", "百年孤独", 
        "人类简史", "活着", "围城", "三体", "平凡的世界",
        "Python编程", "追风筝的人", "小王子", "白夜行"
      ];
      
      const mockAuthors = [
        "N·格里高利·曼昆", "马特·弗里斯比", "加西亚·马尔克斯",
        "尤瓦尔·赫拉利", "余华", "钱钟书", "刘慈欣", "路遥",
        "埃里克·马瑟斯", "卡勒德·胡赛尼", "安托万·德·圣埃克苏佩里", "东野圭吾"
      ];
      
      return Array(6).fill().map((_, i) => {
        const originalPrice = (Math.random() * 50 + 30).toFixed(1);
        const price = isDiscount ? (originalPrice * discountRate).toFixed(1) : originalPrice;
        
        return {
          productId: `secondhand_${Date.now()}_${i}`,
          title: mockTitles[i % mockTitles.length],
          author: mockAuthors[i % mockAuthors.length],
          price: parseFloat(price),
          originalPrice: parseFloat(originalPrice),
          cover: `https://img.yzcdn.cn/vant/apple-${i % 6 + 1}.jpg`,
          sales: Math.floor(Math.random() * 100),
          condition: isNewCondition ? '近新' : ['良好', '一般', '有笔记'][Math.floor(Math.random() * 3)],
          seller: isHot ? `用户${Math.floor(Math.random() * 1000)}` : null,
          discount: isDiscount ? `${(discountRate * 10).toFixed(1)}折` : null
        };
      });
    },
    onDetail(item) {
      this.$router.push({ 
        name: 'productDetail', 
        query: { 
          id: item.productId,
          from: 'secondhand' 
        } 
      });
    },
    // 处理搜索输入
    handleSearchInput() {
      const keyword = this.searchValue.trim().toLowerCase();
      if (!keyword) {
        this.filteredBooks = [];
        return;
      }
      
      // 模糊搜索逻辑：匹配书名、作者
      this.filteredBooks = this.allBooks.filter(book => {
        const titleMatch = book.title.toLowerCase().includes(keyword);
        const authorMatch = book.author && book.author.toLowerCase().includes(keyword);
        return titleMatch || authorMatch;
      });
    },
    // 搜索按钮点击
    onSearch() {
      this.handleSearchInput();
    },
    // 清除搜索
    clearSearch() {
      this.searchValue = '';
      this.filteredBooks = [];
    },
    handleSwipeChange(index) {
      this.currentPage = index;
    }
  }
};
</script>

<style lang="less" scoped>
/* 原有样式保持不变，新增以下样式 */
.search-result-container {
  padding: 10px;
  background-color: #f9f5ed;
  min-height: calc(100vh - 54px);
}

.search-result-list {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.book-card {
  display: flex;
  background-color: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
  padding: 10px;
}

.book-image {
  position: relative;
  margin-right: 10px;
}

.book-tags {
  position: absolute;
  top: 5px;
  left: 5px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.book-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.author {
  font-size: 12px;
  color: #999;
  margin-bottom: 5px;
}

.sales {
  display: flex;
  align-items: center;
  font-size: 12px;
  color: #666;
}

.empty-result {
  padding: 60px 20px;
  text-align: center;
  background-color: white;
  border-radius: 8px;
  
  p {
    margin: 15px 0;
    color: #999;
  }
}

.search-action {
  color: #8b4513;
  font-size: 14px;
  padding: 0 10px;
}

/* 原有样式保持不变 */
.second-hand-book-home {
  background-color: #f9f5ed;
	padding-bottom: 50px;
  
  // 导航栏样式
  .book-nav-bar {
    background-color: #8b4513; // 棕色系
    
    ::v-deep .van-nav-bar__content {
      height: 54px;
    }
    
    .logo-area {
      display: flex;
      align-items: center;
      
      .logo-text {
        color: white;
        font-size: 18px;
        font-weight: bold;
        margin-right: 8px;
        font-family: "楷体", serif;
      }
    }
  }
  
  // 搜索框样式
  .book-search {
    padding: 5px 0;
    width: 240px;
		
    ::v-deep .van-search__content {
      background-color: white;
    }
  }
  
  // 轮播区域
  .swipe-container {
    margin-bottom: 10px;
    
    .book-swipe {
      height: 160px;
      position: relative;
      
      .swipe-tag {
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 1;
      }
    }
    
    .swipe-notice {
      background-color: #f5e8d0;
      padding: 5px 10px;
    }
  }
  
  // 商品区域
    .product-section {
      padding: 10px;
      margin-bottom: 10px;
      background-color: white;
      border-radius: 8px;
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
      
      .section-title {
        font-size: 16px;
        color: #8b4513;
        margin-bottom: 10px;
      }
      
      .product-list {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
      }
      
      .product-card {
        width: calc(50% - 5px);
        margin-bottom: 10px;
        border-radius: 8px;
        overflow: hidden;
        box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
      }
      
      .product-info {
        padding: 10px;
        
        .title {
          font-size: 14px;
          line-height: 1.4;
          color: #333;
          margin-bottom: 5px;
        }
        
        .price-section {
          display: flex;
          align-items: center;
          
          .current-price {
            color: #f44;
            font-size: 16px;
            font-weight: bold;
            margin-right: 8px;
          }
          
          .original-price {
            color: #999;
            font-size: 12px;
            text-decoration: line-through;
          }
        }
      }
    }
  
  // 分类图标样式
  .category-icon {
    width: 36px;
    height: 36px;
    border-radius: 50%;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #f5e8d0;
    
    img, .van-icon {
      width: 24px;
      height: 24px;
      object-fit: contain;
    }
  }
  
  // 功能入口区域
  .menu-section {
    background-color: white;
    padding: 15px 10px;
    margin-bottom: 10px;
    border-radius: 8px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
    
    .section-title {
      display: flex;
      align-items: center;
      font-size: 16px;
      color: #333;
      margin-bottom: 15px;
      padding-left: 5px;
    }
  }
  
  // 快速入口
  .quick-actions {
    margin: 10px 0;
    background-color: white;
    border-radius: 8px;
    padding: 10px 0;
    
    /deep/ .van-grid-item__text {
      color: #8b4513;
      font-size: 12px;
    }
  }
}
</style>